<template>
  <div class="attendance-management">
    <!-- 页面头部 -->
    <div class="flex justify-between items-center mb-6">
      <h1 class="text-2xl font-bold text-gray-800">考勤管理</h1>
      <div class="flex gap-2">
        <el-button type="primary" @click="handleClockIn">
          <el-icon><Clock /></el-icon>
          打卡
        </el-button>
        <el-button type="success" @click="handleLeaveRequest">
          <el-icon><DocumentAdd /></el-icon>
          请假申请
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
      <el-card class="stat-card">
        <div class="flex items-center">
          <div class="stat-icon bg-blue-100 text-blue-600">
            <el-icon size="24"><User /></el-icon>
          </div>
          <div class="ml-4">
            <div class="text-2xl font-bold text-gray-800">{{ stats.totalEmployees }}</div>
            <div class="text-sm text-gray-500">总员工数</div>
          </div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="flex items-center">
          <div class="stat-icon bg-green-100 text-green-600">
            <el-icon size="24"><Check /></el-icon>
          </div>
          <div class="ml-4">
            <div class="text-2xl font-bold text-gray-800">{{ stats.presentToday }}</div>
            <div class="text-sm text-gray-500">今日出勤</div>
          </div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="flex items-center">
          <div class="stat-icon bg-yellow-100 text-yellow-600">
            <el-icon size="24"><Warning /></el-icon>
          </div>
          <div class="ml-4">
            <div class="text-2xl font-bold text-gray-800">{{ stats.lateToday }}</div>
            <div class="text-sm text-gray-500">今日迟到</div>
          </div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="flex items-center">
          <div class="stat-icon bg-red-100 text-red-600">
            <el-icon size="24"><Close /></el-icon>
          </div>
          <div class="ml-4">
            <div class="text-2xl font-bold text-gray-800">{{ stats.absentToday }}</div>
            <div class="text-sm text-gray-500">今日缺勤</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 搜索表单 -->
    <el-card class="mb-6">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="员工姓名">
          <el-input
            v-model="searchForm.employeeName"
            placeholder="请输入员工姓名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="部门">
          <el-select
            v-model="searchForm.department"
            placeholder="请选择部门"
            clearable
            style="width: 150px"
          >
            <el-option label="全部" value="" />
            <el-option label="技术部" value="技术部" />
            <el-option label="销售部" value="销售部" />
            <el-option label="人事部" value="人事部" />
            <el-option label="财务部" value="财务部" />
          </el-select>
        </el-form-item>
        <el-form-item label="考勤状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 150px"
          >
            <el-option label="全部" value="" />
            <el-option label="正常" value="正常" />
            <el-option label="迟到" value="迟到" />
            <el-option label="早退" value="早退" />
            <el-option label="缺勤" value="缺勤" />
            <el-option label="请假" value="请假" />
          </el-select>
        </el-form-item>
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 考勤记录表格 -->
    <el-card>
      <div class="flex justify-between items-center mb-4">
        <h3 class="text-lg font-semibold">考勤记录</h3>
        <el-button type="primary" @click="exportAttendance">
          <el-icon><Download /></el-icon>
          导出考勤
        </el-button>
      </div>
      
      <el-table
        :data="attendanceList"
        style="width: 100%"
        v-loading="loading"
        stripe
        border
      >
        <el-table-column prop="employeeName" label="员工姓名" width="100" />
        <el-table-column prop="employeeNo" label="工号" width="120" />
        <el-table-column prop="department" label="部门" width="100" />
        <el-table-column prop="date" label="日期" width="120" />
        <el-table-column prop="clockInTime" label="上班打卡" width="120" />
        <el-table-column prop="clockOutTime" label="下班打卡" width="120" />
        <el-table-column prop="workHours" label="工作时长" width="100">
          <template #default="{ row }">
            <span class="text-blue-600 font-medium">{{ row.workHours }}h</span>
          </template>
        </el-table-column>
        <el-table-column prop="overtimeHours" label="加班时长" width="100">
          <template #default="{ row }">
            <span class="text-orange-600 font-medium">{{ row.overtimeHours }}h</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="考勤状态" width="100">
          <template #default="{ row }">
            <el-tag
              :type="getStatusType(row.status)"
              size="small"
            >
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="150" />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(row)"
              link
            >
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="flex justify-center mt-6">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 打卡对话框 -->
    <el-dialog
      v-model="clockDialogVisible"
      title="员工打卡"
      width="400px"
    >
      <el-form :model="clockForm" label-width="80px">
        <el-form-item label="员工">
          <el-select v-model="clockForm.employeeId" placeholder="请选择员工" style="width: 100%">
            <el-option
              v-for="emp in employeeOptions"
              :key="emp.id"
              :label="emp.name"
              :value="emp.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="打卡类型">
          <el-radio-group v-model="clockForm.type">
            <el-radio label="上班">上班打卡</el-radio>
            <el-radio label="下班">下班打卡</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="打卡时间">
          <el-date-picker
            v-model="clockForm.time"
            type="datetime"
            placeholder="选择打卡时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="clockForm.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="clockDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleClockSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 请假申请对话框 -->
    <el-dialog
      v-model="leaveDialogVisible"
      title="请假申请"
      width="500px"
    >
      <el-form ref="leaveFormRef" :model="leaveForm" :rules="leaveRules" label-width="100px">
        <el-form-item label="申请人" prop="employeeId">
          <el-select v-model="leaveForm.employeeId" placeholder="请选择申请人" style="width: 100%">
            <el-option
              v-for="emp in employeeOptions"
              :key="emp.id"
              :label="emp.name"
              :value="emp.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="请假类型" prop="leaveType">
          <el-select v-model="leaveForm.leaveType" placeholder="请选择请假类型" style="width: 100%">
            <el-option label="年假" value="年假" />
            <el-option label="病假" value="病假" />
            <el-option label="事假" value="事假" />
            <el-option label="调休" value="调休" />
            <el-option label="婚假" value="婚假" />
            <el-option label="产假" value="产假" />
          </el-select>
        </el-form-item>
        <el-form-item label="请假时间" prop="dateRange">
          <el-date-picker
            v-model="leaveForm.dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="请假天数">
          <el-input-number
            v-model="leaveForm.days"
            :min="0.5"
            :max="365"
            :step="0.5"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="请假原因" prop="reason">
          <el-input
            v-model="leaveForm.reason"
            type="textarea"
            :rows="3"
            placeholder="请输入请假原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="leaveDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleLeaveSubmit">提交申请</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Clock,
  DocumentAdd,
  User,
  Check,
  Warning,
  Close,
  Search,
  Refresh,
  Download,
  Edit
} from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const clockDialogVisible = ref(false)
const leaveDialogVisible = ref(false)
const leaveFormRef = ref()

// 统计数据
const stats = reactive({
  totalEmployees: 156,
  presentToday: 142,
  lateToday: 8,
  absentToday: 6
})

// 搜索表单
const searchForm = reactive({
  employeeName: '',
  department: '',
  status: '',
  dateRange: []
})

// 打卡表单
const clockForm = reactive({
  employeeId: '',
  type: '上班',
  time: new Date(),
  remark: ''
})

// 请假表单
const leaveForm = reactive({
  employeeId: '',
  leaveType: '',
  dateRange: [],
  days: 1,
  reason: ''
})

// 请假表单验证规则
const leaveRules = {
  employeeId: [
    { required: true, message: '请选择申请人', trigger: 'change' }
  ],
  leaveType: [
    { required: true, message: '请选择请假类型', trigger: 'change' }
  ],
  dateRange: [
    { required: true, message: '请选择请假时间', trigger: 'change' }
  ],
  reason: [
    { required: true, message: '请输入请假原因', trigger: 'blur' },
    { min: 5, max: 200, message: '请假原因长度在 5 到 200 个字符', trigger: 'blur' }
  ]
}

// 员工选项
const employeeOptions = ref([
  { id: 1, name: '张三' },
  { id: 2, name: '李四' },
  { id: 3, name: '王五' },
  { id: 4, name: '赵六' },
  { id: 5, name: '孙七' }
])

// 考勤列表
const attendanceList = ref([])

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    '正常': 'success',
    '迟到': 'warning',
    '早退': 'warning',
    '缺勤': 'danger',
    '请假': 'info'
  }
  return statusMap[status] || 'info'
}

// 获取考勤列表
const getAttendanceList = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 模拟数据
    const mockData = [
      {
        id: 1,
        employeeName: '张三',
        employeeNo: 'EMP001',
        department: '技术部',
        date: '2024-01-15',
        clockInTime: '09:00:00',
        clockOutTime: '18:00:00',
        workHours: 8,
        overtimeHours: 0,
        status: '正常',
        remark: ''
      },
      {
        id: 2,
        employeeName: '李四',
        employeeNo: 'EMP002',
        department: '销售部',
        date: '2024-01-15',
        clockInTime: '09:15:00',
        clockOutTime: '18:30:00',
        workHours: 8,
        overtimeHours: 0.5,
        status: '迟到',
        remark: '交通堵塞'
      },
      {
        id: 3,
        employeeName: '王五',
        employeeNo: 'EMP003',
        department: '人事部',
        date: '2024-01-15',
        clockInTime: '08:55:00',
        clockOutTime: '17:45:00',
        workHours: 7.5,
        overtimeHours: 0,
        status: '早退',
        remark: '有事提前离开'
      },
      {
        id: 4,
        employeeName: '赵六',
        employeeNo: 'EMP004',
        department: '财务部',
        date: '2024-01-15',
        clockInTime: '',
        clockOutTime: '',
        workHours: 0,
        overtimeHours: 0,
        status: '请假',
        remark: '病假'
      },
      {
        id: 5,
        employeeName: '孙七',
        employeeNo: 'EMP005',
        department: '市场部',
        date: '2024-01-15',
        clockInTime: '09:00:00',
        clockOutTime: '20:00:00',
        workHours: 8,
        overtimeHours: 3,
        status: '正常',
        remark: '项目加班'
      }
    ]
    
    attendanceList.value = mockData
    pagination.total = mockData.length
  } catch (error) {
    ElMessage.error('获取考勤列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  getAttendanceList()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    employeeName: '',
    department: '',
    status: '',
    dateRange: []
  })
  handleSearch()
}

// 打卡
const handleClockIn = () => {
  clockForm.time = new Date()
  clockDialogVisible.value = true
}

// 打卡提交
const handleClockSubmit = async () => {
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    ElMessage.success('打卡成功')
    clockDialogVisible.value = false
    getAttendanceList()
  } catch (error) {
    ElMessage.error('打卡失败')
  }
}

// 请假申请
const handleLeaveRequest = () => {
  Object.assign(leaveForm, {
    employeeId: '',
    leaveType: '',
    dateRange: [],
    days: 1,
    reason: ''
  })
  leaveDialogVisible.value = true
}

// 请假提交
const handleLeaveSubmit = async () => {
  try {
    await leaveFormRef.value.validate()
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    ElMessage.success('请假申请提交成功')
    leaveDialogVisible.value = false
    getAttendanceList()
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 编辑考勤
const handleEdit = (row) => {
  ElMessage.info('编辑考勤功能开发中...')
}

// 导出考勤
const exportAttendance = () => {
  ElMessage.success('考勤数据导出成功')
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  getAttendanceList()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  getAttendanceList()
}

// 组件挂载时获取数据
onMounted(() => {
  getAttendanceList()
})
</script>

<style scoped>
.attendance-management {
  padding: 20px;
}

.stat-card {
  cursor: pointer;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.search-form .el-form-item {
  margin-bottom: 0;
}

.dialog-footer {
  text-align: right;
}
</style>